<script lang="ts" setup>
import {ElButton, ElInput, ElTree} from 'element-plus';
import RDialog, {Rdialog} from "@/components/r-dialog.vue";
import {onMounted, Ref, ref} from 'vue';
import {SuitcaseLine} from '@element-plus/icons-vue';

import treeRender from './tree-render.vue'
import {get} from "@/request.ts";
import _ from 'lodash'

// 数据
const tree_data = ref([])
// 结果数组
const result = ref([])
// 搜索关键字
const search_key = ref('')
// 搜索后的数据
const search_data = ref([])
// 模态框
const show = ref(false)
// props
const props = defineProps({
  modelVal: Array,
  default: [],
})
// emit
const emit = defineEmits(['update:modelVal'])

const tree_render = (h, {node, data, store}) => {
  return h(treeRender, {data, modelVal: result})
}

const enter = () => {
  emit('update:modelVal', result.value)
  show.value = false
}

const tree_search = _.debounce(async () => {
  search_data.value = (await get('/tree_data', {search_key: search_key.value})).data
}, 1000)

const close = () => show.value = false

const get_tree_data = async () => tree_data.value = (await get('/tree_data')).data
onMounted(get_tree_data)
</script>

<template>
  <div class="w-full flex">
    <el-input/>
    <el-button :type="'primary'" class="hover:underline" style="border-radius: 0;" @click="show = true">
      选择
    </el-button>
  </div>
  <el-tree/>

  <r-dialog v-model="show" :draggable="true" width="350">
    <template #header>
      请选择
    </template>

    <div class="w-full">
      <div class="w-full flex pl-2 pr-2 ">
        <el-input v-model="search_key" @input="tree_search"/>
        <el-button link>查找</el-button>
      </div>
    </div>

    <div>
      <el-tree v-if="search_data.length === 0" :data="tree_data" :icon="SuitcaseLine" :render-content="tree_render"/>
      <div v-else>
        <div v-for="item in search_data" :key="item._id">
            <div>{{ item.name }}</div>
            <el-checkbox/>
        </div>
      </div>
    </div>

    <template #footer>
      <div>
        <el-button :type="'danger'" @click="get_tree_data">刷新数据</el-button>
        <el-button :type="'danger'" @click="close">取消</el-button>
        <el-button :type="'primary'" @click="enter">确定</el-button>
      </div>
    </template>
  </r-dialog>
</template>